package validate

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/locales/zh"
	"github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"reflect"
	"regexp"
	"strings"
)

var (
	uni   *ut.UniversalTranslator
	trans ut.Translator
)

func init() {
	//注册翻译器
	zh := zh.New()
	uni = ut.New(zh, zh)

	trans, _ = uni.GetTranslator("zh")
	//获取gin的校验器
	validate, _ := binding.Validator.Engine().(*validator.Validate)

	//取出中文字段名
	validate.RegisterTagNameFunc(func(fld reflect.StructField) string {

		name := strings.SplitN(fld.Tag.Get("zh"), ",", 2)[0]
		if name == "-" {
			return ""
		}

		return name
	})

	_ = validate.RegisterValidation("phoneCheck", phoneCheck)
	_ = validate.RegisterTranslation("phoneCheck", trans, func(ut ut.Translator) error {
		//return ut.Add("phoneCheck", "{0} 手机号格式不正确", true)
		return ut.Add("phone", "手机号格式不正确", true)

	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("phone", fe.Field())
		return t
	})

	_ = validate.RegisterValidation("idCardCheck", idCardCheck)
	_ = validate.RegisterTranslation("idCardCheck", trans, func(ut ut.Translator) error {
		return ut.Add("id_card", "身份证格式不正确", true)

	}, func(ut ut.Translator, fe validator.FieldError) string {
		t, _ := ut.T("id_card", fe.Field())
		return t
	})

	//注册翻译器
	_ = zh_translations.RegisterDefaultTranslations(validate, trans)

}

//Translate 翻译错误信息
func Translate(err error, c *gin.Context) {
	var result = make([]string, 0)

	switch err.(type) {

	case validator.ValidationErrors:
		errors := err.(validator.ValidationErrors)
		for _, err := range errors {
			result = append(result, err.Translate(trans))
		}

	case *json.UnmarshalTypeError:
		jsonErr := err.(*json.UnmarshalTypeError)
		result = append(result, jsonErr.Field+"类型转化错误")
	}

	c.Set("code", "00006")
	c.Set("data", result)
}

//校验手机号
func phoneCheck(fl validator.FieldLevel) bool {
	phone := fl.Field().String()
	if len(phone) == 0 {
		return true
	}

	reg := `^1([38][0-9]|14[57]|5[^4])\d{8}$`
	rgx := regexp.MustCompile(reg)

	return rgx.MatchString(phone)
}

//校验身份证
func idCardCheck(fl validator.FieldLevel) bool {
	idCard := fl.Field().String()
	idCard = strings.ToUpper(idCard)
	if len(idCard) == 0 {
		return true
	}

	reg := `(^\d{15}$)|(^\d{17}([0-9]|X)$)`
	rgx := regexp.MustCompile(reg)

	if false == rgx.MatchString(idCard) {
		return false
	}
	return true
	//if 15 == len(idCard) {
	//	//15位
	//
	//}else  {
	//	//18位
	//}
}
